package com.emm.yixun.mobile.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;

import com.alibaba.fastjson.JSONObject;
import com.emm.yixun.mobile.R;
import com.emm.yixun.mobile.adapter.MainHousingFragmentAdapter;
import com.emm.yixun.mobile.application.EmmApplication;
import com.emm.yixun.mobile.base.BaseActivity;
import com.emm.yixun.mobile.model.GetHousesList;
import com.eroad.product.tools.MyListView;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.yixun.app.viewpagerandimag.sample.ViewPagerActivity;

import java.util.HashMap;
import java.util.Map;

import xf.tools.Loading;

/**
 * <p>
 * <b>Title：</b> 房源
 * </p>
 * <p>
 * <b>Description：</b>
 * </p>
 *
 * @author tangxin
 * @date 2016年12月13日 下午6:17:45
 */
public class HousingResourcesFragment extends Fragment {

    private static final String TAG = "HousingResources";

    FragmentActivity root;

    /**
     * 房源列表
     */
    MyListView listview;

    /**
     * 房源适配器
     */
    MainHousingFragmentAdapter adapter;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.housing_resources_fragment, null);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        root = getActivity();

        initView();

        // 获取数据
        GetHousesList();
    }

    /**
     * <p>
     * <b>Title：</b> 初始化listview
     * </p>
     * <p>
     * <b>Description：</b>
     * </p>
     *
     * @author tangxin
     * @date 2016年12月7日 上午11:33:38
     */
    private void initView() {
        listview = (MyListView) root.findViewById(R.id.listview);
        RelativeLayout main_head_top_rela = (RelativeLayout) root.findViewById(R.id.housing_include).findViewById(
                R.id.main_head_top_rela);
        BaseActivity.SetViewHeight(main_head_top_rela);// 更改relativelayout的高度
    }

    /**
     * <p>
     * <b>Title：</b> 刷新
     * </p>
     * <p>
     * <b>Description：</b>
     * </p>
     *
     * @author tangxin
     * @date 2016年12月7日 上午11:35:11
     */
    public void Reload() {
        GetHousesList();
    }

    /**
     * 查询房源列表接口
     */
    GetHousesList gethouse;

    /**
     * <p>
     * <b>Title：</b> 房源列表查询
     * </p>
     * <p>
     * <b>Description：</b>
     * </p>
     *
     * @author tangxin
     * @date 2016年12月7日 上午11:35:27
     */
    private void GetHousesList() {
        EmmApplication.updateUrl("getHousesList");
        Map<String, String> map = new HashMap<String, String>();
        map.put("version", EmmApplication.getPackageManager(5));
        map.put("merchantId", EmmApplication.getData(EmmApplication.merchantId));
        map.put("token", EmmApplication.getToken());
        map.put("userId", EmmApplication.getUserId());
        map.put("projectId", EmmApplication.getProjectID());
        map.put("projectCode", EmmApplication.getProjectCode());
        map.put("terminalCode", EmmApplication.getPackageManager(2));
        Map<String, Object> paramsMap = new HashMap<String, Object>();
        paramsMap.put("params", map);
        JSONObject json = new JSONObject(paramsMap);
        String jsonstr = json.toString();
        RequestParams params = new RequestParams();
        params.put("body", jsonstr);
        Log.v(TAG, "getHousesList-->post" + EmmApplication.urlStr + "?body=" + jsonstr);
        AsyncHttpClient asyncHttpClient = new AsyncHttpClient();
        asyncHttpClient.post(EmmApplication.urlStr, params, new AsyncHttpResponseHandler() {
            @Override
            public void onFailure(Throwable error, String content) {
                super.onFailure(error, content);
                Loading.hideDialogForLoading();
                Log.v(TAG, "请求结束error:" + error + "==" + content);
            }

            @Override
            public void onFinish() {
                Loading.hideDialogForLoading();
                Log.v(TAG, "请求结束");
                super.onFinish();
            }

            @Override
            public void onStart() {
                super.onStart();
                Loading.showDialogForLoading(root, "正在加载...", false, true, 60000);
                Log.v(TAG, "请求开始");
            }

            @Override
            public void onSuccess(String content) {
                super.onSuccess(content);
                if (content == null) {
                    return;
                }
                Log.v(TAG, content);

                JSONObject jsonObj = JSONObject.parseObject(content);
                JSONObject resData = (JSONObject) jsonObj.get("resData");
                if (resData == null) {
                    Log.v(TAG, "信息返回值为空");
                    return;
                }

                gethouse = JSONObject.parseObject(resData.toString(), GetHousesList.class);

                if ("1".equals(gethouse.getResult())) {
                    Log.v("获取成功", "");
                    if (null == adapter) {
                        // 数据源设置
                        adapter = new MainHousingFragmentAdapter(gethouse.getPremisesList(), root);
                        listview.setAdapter(adapter);// 绑定适配器
                    } else {
                        adapter.SetDate(gethouse.getPremisesList());
                    }
                } else {
                    EmmApplication.Ts(gethouse.getErrorMsg().toString());
                    Log.v("获取失败", "errorCode:" + gethouse.getErrorCode().toString() + "errorMsg:"
                            + gethouse.getErrorMsg().toString());
                }
            }
        });
    }

    /**
     * <p>
     * <b>Title：</b> 打开总平图
     * </p>
     * <p>
     * <b>Description：</b>
     * </p>
     *
     * @author tangxin
     * @date 2016年12月7日 上午11:36:52
     */
    public void OpenBigJpg() {
        if (null == gethouse || null == gethouse.getFlatMapList() || gethouse.getFlatMapList().size() <= 0) {
            EmmApplication.Ts("当前没有总平图");
        } else {// 跳转图片预览
            // 属性配置
            ViewPagerActivity.postion = 0;// 首先展示的图片下标
            // 首先重置列表，避免缓存存在。 图片列表，若为本地，add前先拼接file://
            ViewPagerActivity.sDrawables.clear();
            for (int u = 0; u < gethouse.getFlatMapList().size(); u++) {// 逐个加入
                ViewPagerActivity.sDrawables.add(gethouse.getFlatMapList().get(u).getFlatMapUrl());
            }
            // 跳转
            Intent intent = new Intent(root, ViewPagerActivity.class);
            intent.putExtra("IsSetName", 1);
            startActivity(intent);
        }
    }
}
